package com.github.ilioili.justdoit.widget;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import java.util.Calendar;
import java.util.Date;

/**
 * Created by hantuo on 16/5/10.
 */
public class YearView extends RecyclerView {

    private Date date= new Date();
    private final Adapter adapter = new Adapter() {
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ViewHolder(itemAdapter.getView()) {
                @Override
                public String toString() {
                    return super.toString();
                }
            };
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            long time = (-offsetDayCount+position)*1000l*60*60*24;
            date.setTime(time);
            calendar.setTime(date);
            int year = calendar.get(Calendar.YEAR);
            int month= calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            itemAdapter.bindView(holder.itemView, year, month, day);
        }

        @Override
        public int getItemCount() {
            return line*7;
        }
    };
    private int offsetDayCount;
    private int line;
    private Calendar calendar = Calendar.getInstance();

    public YearView(Context context) {
        this(context, null);
    }

    public YearView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public YearView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, 2050);
        calendar.set(Calendar.MONTH, Calendar.UNDECIMBER);
        calendar.set(Calendar.DAY_OF_MONTH, 31);
        offsetDayCount = calendar.get(Calendar.DAY_OF_WEEK);
        long offset = offsetDayCount * 1000 * 60 * 60 * 24;
        long time = calendar.getTime().getTime() + offset;
        line = (int) (time / 1000 / 60 / 60 / 24 / 7);
        setLayoutManager(new GridLayoutManager(context, 7));
        setAdapter(adapter);
    }

    public void setItemAdapter(ItemAdapter itemAdapter) {
        this.itemAdapter = itemAdapter;
    }

    private ItemAdapter itemAdapter;

    public static abstract class ItemAdapter {

        public abstract View getView();

        /**
         * @param year
         * @param month
         * @param day
         */
        public abstract void bindView(View view, int year, int month, int day);
    }

}
